package org.xqh.test.yzs.shimao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.google.common.collect.Maps;
import org.springframework.util.StringUtils;
import org.xqh.utils.DateUtil;
import org.xqh.utils.ThreadPoolUtils;
import org.xqh.utils.excel.ExcelExportUtil;
import org.xqh.utils.file.ReadTxtFileUtils;
import org.xqh.utils.http.FxHttpClientUtils;
import org.xqh.utils.http.HttpRetModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.stream.Collectors;

/**
 * @ClassName SpaceDeviceInfoExport
 * @Description 空间设备信息导出
 * @Author xuqianghui
 * @Date 2020/12/10 9:41
 * @Version 1.0
 */
public class SpaceDeviceInfoExport {

    public final static String hb_url = "http://route.igaicloud.cn:8088/monitor/admin/hbRecordPage";

    public final static String work_path = "E:\\document\\yzs\\program\\shimao-iot\\";

    public final static Map<String, String> map = new HashMap<String, String>(){{
        put("SHSSYMZPHOTELL01", "上海佘山茂御臻品之选酒店");
        put("SMSHHJAMHOTELL01", "世茂皇家艾美酒店");
        put("WYSSMYRZHOTELL01", "武夷山世茂御榕庄酒店");
        put("GBDSMSYJDHOTELL01", "高碑店世茂世御酒店");
        put("SMWHFXHOTELL01", "武汉江滩世茂凡象酒店");
    }};

    /**
     * 智慧社区 空间ID
     * [2000242,2000246,2000254,2000292,2000632,2000635,2006053,2006079,2006370,2006548,2006569,2006595,2006602,2006609,2006752,2006829,2009395,2009451,2009457]
     * 酒店空间ID
     * [1392,2006752,965,2000248,1255,2006480,1000239,2650,2006005,2006476,2434,537,2449,1360,1359,503,2008941,683,1332,2000269]
     */
    public static void parseAllSpaceId(){
        String str = ReadTxtFileUtils.readJson(new File(work_path + "酒店-空间.txt"));
        List<HotelSpaceId> list = JSONArray.parseArray(str, HotelSpaceId.class);
        System.out.println(JSON.toJSONString(list.stream().map(HotelSpaceId::getSpace_id).collect(Collectors.toList())));
    }

    public final static String split_str = "\\|";

    public static void main1111(String[] args) {
        String path = "酒店管理集团|GBDSMSYJDHOTELL01|1栋|5层|8509";
        for(String key:map.keySet()){
            path = path.replaceAll(key, map.get(key));
        }
        System.out.println(path.substring(path.indexOf("高碑店世茂世御酒店") + "高碑店世茂世御酒店".length() + 1));
        System.out.println(path);
    }

    public static void main222(String[] args) {
        parseAllSpaceId();
    }

    public static List<String> parseHotelDeviceIdList(String fileName){
        List<String> list = ReadTxtFileUtils.readTxt(new File(work_path + fileName));
        return list;
    }
    public static void main(String[] args) {
        List<QuerySpaceDeviceInfoRet> list = parseDeviceList("武汉凡象-设备数据.txt");
        List<String> deviceList = parseHotelDeviceIdList("fanxiang.txt");
        list = list.stream().filter(l-> deviceList.contains(l.getDeviceCode())).collect(Collectors.toList());
        for (QuerySpaceDeviceInfoRet d:list){
            FutureTask<DeviceVerRet> futureTask = new FutureTask<>(new QueryDeviceVersionThread(d.getDeviceCode()));
            ThreadPoolUtils.submit(futureTask);
            d.setFutureTask(futureTask);
        }

        list.stream().forEach(d-> {
            try {
                DeviceVerRet deviceVerRet = d.getFutureTask().get();
                d.setDeviceVersion(deviceVerRet.getVersion_number());
                if(Objects.nonNull(deviceVerRet.getUp_time())){
                    Date upDate = new Date(deviceVerRet.getUp_time() * 1000);
                    if(DateUtil.plusDate(upDate, 2, ChronoUnit.MINUTES).compareTo(new Date()) >= 0){
                        d.setOnline("在线");
                    }
                }
                if(StringUtils.isEmpty(d.getOnline())){
                    d.setOnline("离线");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            for(String key:map.keySet()){
                if(d.getSpacePath().contains(key)){
                    d.setSpacePath(d.getSpacePath().replaceAll(key, map.get(key)));
                }
            }
            String[] arr = d.getSpacePath().split(split_str);
            d.setHotelName(arr[1]);
            d.setRoomPath(d.getSpacePath().substring(d.getSpacePath().indexOf(d.getHotelName()) + d.getHotelName().length() + 1));
        });
        Map<String, List<QuerySpaceDeviceInfoRet>> dataMap = list.stream().collect(Collectors.groupingBy(QuerySpaceDeviceInfoRet::getHotelName));
        for(Entry<String, List<QuerySpaceDeviceInfoRet>> entry:dataMap.entrySet()){
            exportExcel(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 一个酒店导出 一个excel
     * @param hotelName
     * @param list
     */
    public static void exportExcel(String hotelName, List<QuerySpaceDeviceInfoRet> list){
        String[] headers = {"设备归属空间", "归属房间信息", "UDID", "版本号", "设备名称", "设备类型", "设备类型编码", "是否在线"};
        String[] properties = {"hotelName", "roomPath", "deviceCode", "deviceVersion", "deviceName", "deviceTypeName", "deviceTypeCode", "online"};
        ExcelExportUtil.export(headers, properties, list, false, work_path + hotelName);
    }

    public static List<QuerySpaceDeviceInfoRet> parseDeviceList(String fileName){
        String str = ReadTxtFileUtils.readJson(new File(work_path + fileName));
        JSONObject json = JSON.parseObject(str);
        return JSONArray.parseArray(json.getString("data"), QuerySpaceDeviceInfoRet.class);
    }

    public static class QueryDeviceVersionThread implements Callable<DeviceVerRet>{

        private String deviceCode;

        public QueryDeviceVersionThread(String deviceCode){
            this.deviceCode = deviceCode;
        }

        @Override
        public DeviceVerRet call() throws Exception {
            return getDeviceApkVersion(deviceCode);
        }
    }



    public static DeviceVerRet getDeviceApkVersion(String deviceCode){
        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("pageNo", 1);
        reqMap.put("pageSize", 2);
        reqMap.put("deviceSn", deviceCode);
        HttpConfig config = FxHttpClientUtils.getPostJsonConfig(hb_url, null, JSON.toJSONString(reqMap));
        try {
            RequestRet reqRet = FxHttpClientUtils.requestReturnObj(config, RequestRet.class, getModel());
            return reqRet.getContent().get(0);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return null;
    }

    public static HttpRetModel getModel(){
        return HttpRetModel.builder()
                .dataKey("data")
                .statusKey("status")
                .successVal("0")
                .msgKey("message")
                .build();
    }

    @Data
    public static class RequestRet{
        private List<DeviceVerRet> content;
    }

    @Data
    public static class DeviceVerRet{
        private String deviceSn;
        private Long up_time;
        private String version_number;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class QuerySpaceDeviceInfoRet{
        private String spaceName;
        private Long spaceId;
        private String spaceTypeName;
        private String spaceTypeCode;
        private String spacePath;
        private List<Long> spaceTreeInfo;
        private String deviceId;
        private String deviceCode;
        private String deviceName;
        private String deviceTypeCode;
        private String deviceTypeName;
        private String deviceVersion;//暂时没地方取
        private FutureTask<DeviceVerRet> futureTask;
        private String hotelName;
        private String roomPath;
        private String online;//是否在线
    }

    @Data
    public static class HotelSpaceId{
        private String hotel_name;
        private Long space_id;
    }



}
